<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <div class="logo">
          <img src="@/assets/logo.png" alt="汽车租赁平台">
          <h1>汽车租赁平台</h1>
        </div>
      </div>
      
      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="账号密码登录" name="account">
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                prefix-icon="el-icon-user"
                placeholder="用户名/手机号"
                clearable
              ></el-input>
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                prefix-icon="el-icon-lock"
                placeholder="密码"
                show-password
                clearable
              ></el-input>
            </el-form-item>
            
            <el-form-item class="remember-row">
              <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
              <el-button type="text" @click="forgotPassword">忘记密码?</el-button>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" :loading="loading" @click="handleLogin" class="submit-btn">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="手机验证码登录" name="phone">
          <el-form ref="smsForm" :model="smsForm" :rules="smsRules" class="login-form">
            <el-form-item prop="phone">
              <el-input
                v-model="smsForm.phone"
                prefix-icon="el-icon-mobile-phone"
                placeholder="手机号"
                clearable
              ></el-input>
            </el-form-item>
            
            <el-form-item prop="code">
              <div class="code-input-group">
                <el-input
                  v-model="smsForm.code"
                  prefix-icon="el-icon-message"
                  placeholder="验证码"
                  clearable
                ></el-input>
                <el-button 
                  type="primary" 
                  :disabled="isSending" 
                  @click="sendCode" 
                  class="send-code-btn"
                >
                  {{ sendBtnText }}
                </el-button>
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" :loading="loading" @click="handleSmsLogin" class="submit-btn">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      
      <div class="form-footer">
        <p>还没有账号? <el-button type="text" @click="goToRegister">立即注册</el-button></p>
      </div>
      
      <div class="login-options">
        <p class="options-title">其他登录方式</p>
        <div class="options-list">
          <el-button circle icon="el-icon-chat-dot-square" @click="otherLogin('wechat')"></el-button>
          <el-button circle icon="el-icon-s-promotion" @click="otherLogin('weibo')"></el-button>
        </div>
      </div>
    </div>
    
    <div class="background-image"></div>
  </div>
</template>

<script>
import { sendSmsCode } from '@/api/user'

export default {
  name: 'Login',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      const phoneReg = /^1[3-9]\d{9}$/
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!phoneReg.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }

    return {
      activeTab: 'account',
      loginForm: {
        username: '',
        password: ''
      },
      smsForm: {
        phone: '',
        code: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
        ]
      },
      smsRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码长度为6位', trigger: 'blur' }
        ]
      },
      rememberMe: false,
      loading: false,
      isSending: false,
      countdown: 60,
      sendBtnText: '获取验证码',
      timer: null
    }
  },
  methods: {
    // 账号密码登录
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$message.success('登录成功')
              this.$router.push({ path: this.redirect || '/' })
            })
            .catch(error => {
              this.$message.error(error.message || '登录失败，请检查用户名和密码')
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    
    // 短信验证码登录
    handleSmsLogin() {
      this.$refs.smsForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/loginBySms', this.smsForm)
            .then(() => {
              this.$message.success('登录成功')
              this.$router.push({ path: this.redirect || '/' })
            })
            .catch(error => {
              this.$message.error(error.message || '登录失败，请检查手机号和验证码')
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    
    // 发送验证码
    sendCode() {
      this.$refs.smsForm.validateField('phone', (errorMsg) => {
        if (!errorMsg) {
          this.isSending = true
          this.countdown = 60
          this.sendBtnText = `${this.countdown}秒后重发`
          
          sendSmsCode(this.smsForm.phone)
            .then(response => {
              this.$message.success('验证码发送成功，请注意查收')
              // 演示/测试环境自动填充验证码
              if (response && response.code) {
                this.smsForm.code = response.code
              }
              
              this.timer = setInterval(() => {
                if (this.countdown > 0) {
                  this.countdown--
                  this.sendBtnText = `${this.countdown}秒后重发`
                } else {
                  clearInterval(this.timer)
                  this.isSending = false
                  this.sendBtnText = '获取验证码'
                }
              }, 1000)
            })
            .catch(error => {
              this.isSending = false
              this.sendBtnText = '获取验证码'
              this.$message.error(error.message || '验证码发送失败，请稍后重试')
            })
        }
      })
    },
    
    forgotPassword() {
      this.$message.info('忘记密码功能开发中...')
    },
    goToRegister() {
      this.$router.push('/register')
    },
    otherLogin(type) {
      this.$message.info(`${type}登录功能开发中...`)
    },
    
    // 组件销毁前清除定时器
    beforeDestroy() {
      if (this.timer) {
        clearInterval(this.timer)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  .background-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url('https://img.zcool.cn/community/0190a45af3ef2ea801214a3ef43446.jpg@1280w_1l_2o_100sh.jpg') no-repeat center center;
    background-size: cover;
    filter: brightness(0.7);
    z-index: -1;
  }
  
  .login-box {
    width: 400px;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 10px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
    padding: 30px;
    position: relative;
    z-index: 1;
    
    .login-header {
      margin-bottom: 20px;
      text-align: center;
      
      .logo {
        display: flex;
        align-items: center;
        justify-content: center;
        
        img {
          height: 40px;
          margin-right: 10px;
        }
        
        h1 {
          font-size: 22px;
          margin: 0;
          color: #333;
        }
      }
    }
    
    .login-tabs {
      margin-bottom: 15px;
    }
    
    .login-form {
      .form-title {
        font-size: 20px;
        text-align: center;
        margin-bottom: 25px;
        font-weight: 500;
      }
      
      .remember-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
      }
      
      .code-input-group {
        display: flex;
        
        .el-input {
          flex: 1;
        }
        
        .send-code-btn {
          width: 120px;
          margin-left: 10px;
          font-size: 12px;
        }
      }
      
      .submit-btn {
        width: 100%;
      }
    }
    
    .form-footer {
      text-align: center;
      margin: 15px 0;
      color: #666;
    }
    
    .login-options {
      margin-top: 20px;
      text-align: center;
      
      .options-title {
        position: relative;
        display: inline-block;
        padding: 0 10px;
        background-color: rgba(255, 255, 255, 0.95);
        margin-bottom: 15px;
        color: #999;
        
        &::before, &::after {
          content: '';
          position: absolute;
          top: 50%;
          width: 60px;
          height: 1px;
          background-color: #eee;
        }
        
        &::before {
          left: -60px;
        }
        
        &::after {
          right: -60px;
        }
      }
      
      .options-list {
        display: flex;
        justify-content: center;
        
        .el-button {
          margin: 0 10px;
        }
      }
    }
  }
}

@media (max-width: 576px) {
  .login-container {
    .login-box {
      width: 90%;
      padding: 20px;
    }
  }
}
</style> 